### XOR problem example for ffnet ###

from ffnet import ffnet, mlgraph
import random

import Image, os, datetime

DIR = 'data4'
LOG = 'samples'
NET = 'neural.net'
PATTERN = 1

t1 = datetime.datetime.today()

f = open(os.path.join(DIR, LOG), 'r')

d = f.readline().split(':')

im = Image.open(os.path.join(DIR, d[0]))
resx, resy = im.size
INPUTS = resx * resy

# Generate standard layered network architecture and create network
conec = mlgraph((INPUTS, 8, 3))
net = ffnet(conec)

# Define training data

input, target = [], []

for s in f:
    d = s.split(':')
    im = Image.open(os.path.join(DIR, d[0]))

    l = []

    for i in im.getdata():
        l.append(i[1])

    input.append(l)

    #input.append(list(im.getdata()))

    distance = d[1]
    degrees = d[2]
    target.append([distance] + [degrees] + [PATTERN])

# Train network
#first find good starting point with genetic algorithm (not necessary, but may be helpful)
#print "FINDING STARTING WEIGHTS WITH GENETIC ALGORITHM..."
#net.train_genetic(input, target, individuals=20, generations=500)
#then train with scipy tnc optimizer
print "TRAINING NETWORK..."
net.train_tnc(input, target, maxfun = 1000, messages=1)
#net.train_momentum(input, target)

t2 = datetime.datetime.today()

print 'Final time: ' + str(t2 - t1)

# Test network
#print
#print "TESTING NETWORK..."
#output, regression = net.test(input, target, iprint = 2)

# Save/load/export network
from ffnet import savenet, loadnet, exportnet
print "Network is saved..."
savenet(net, os.path.join(DIR, NET))
